<template>
    <BaseParam :label="label" :help="help">
        <div class="tags-param">
            <el-tag
                v-for="tag in tags"
                :key="tag"
                closable
                :disable-transitions="false"
                @close="handleClose(tag)"
            >
                {{ tag }}
            </el-tag>
            <el-input
                v-if="inputVisible"
                ref="inputRef"
                v-model="inputValue"
                class="tag-input"
                size="small"
                @keyup.enter="handleInputConfirm"
                @blur="handleInputConfirm"
            />
            <el-button v-else class="button-new-tag" size="small" @click="showInput">
                + 添加标签
            </el-button>
        </div>
    </BaseParam>
</template>

<script lang="ts" setup>
import { ref, watch, nextTick } from 'vue';
import BaseParam from './BaseParam.vue';
import type { ParamConfig } from './types';

const props = defineProps<{
    modelValue?: string[];
    label: string;
    help?: string;
    config?: {
        maxTags?: number;
        maxLength?: number;
        suggestions?: string[];
    };
}>();

const emit = defineEmits<{
    (e: 'update:modelValue', value: string[]): void;
}>();

const tags = ref<string[]>(props.modelValue || []);
const inputVisible = ref(false);
const inputValue = ref('');
const inputRef = ref<HTMLInputElement>();

watch(() => props.modelValue, (newValue) => {
    tags.value = newValue || [];
});

const handleClose = (tag: string) => {
    tags.value = tags.value.filter((t) => t !== tag);
    emit('update:modelValue', tags.value);
};

const showInput = () => {
    inputVisible.value = true;
    nextTick(() => {
        inputRef.value?.focus();
    });
};

const handleInputConfirm = () => {
    if (inputValue.value) {
        if (!tags.value.includes(inputValue.value)) {
            tags.value.push(inputValue.value);
            emit('update:modelValue', tags.value);
        }
    }
    inputVisible.value = false;
    inputValue.value = '';
};
</script>

<style lang="scss" scoped>
.tags-param {
    .el-tag {
        margin-right: 8px;
        margin-bottom: 8px;
    }

    .tag-input {
        width: 100px;
        margin-right: 8px;
        vertical-align: bottom;
    }

    .button-new-tag {
        margin-bottom: 8px;
    }
}
</style> 